<?php
session_start();
function success(){
    $result = [
        'error'=> 0,
        'message' => '成功'
    ];
    return json_encode($result);
}
function error($msg){
    $data = [
        'error'=> 1,
        'message' => $msg
    ];
    return json_encode($data);
}
if(empty($_POST['username'])){
    die(error('用户名不能为空'));
}
if(empty($_POST['password'])){
    die(error('密码不能为空'));
}
$username = $_POST['username'];
$password = $_POST['password'];
try{
    $db = new PDO('mysql:dbname=qq;host=127.0.0.1','root','123456');
    $statement = $db ->prepare('select * from userinfo where name=:username');
    if($statement->execute([':username'=> $username])===false)
        throw new PDOException($statement->errorInfo()[2]);
    $result = $statement->fetch();
}catch (PDOException $e){
    echo $e -> getMessage();
}
if($username != $result['name']){
    die(error('用户不存在'));
}
if($password != $result['password']){
    die(error('密码不正确'));
}

$_SESSION['user'] = $result['name'];
echo success();